﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

using BodaNetCommunications.Utilities.ComTypes;

namespace BodaNetCommunications.Utilities.DataLibs
{
    public class UShortLib
    {
        public static ushort GetUShortFromByteArray(byte[] source, int start = 0, EndianType type = EndianType.ABCD)
        {
            return BitConverter.ToUInt16(ByteArrayLib.Get2ByteArray(source, start, type), 0);
        }

        public static ushort[] GetUShortArrayFromByteArray(byte[] source, EndianType type = EndianType.ABCD)
        {
            ushort[] array = new ushort[source.Length / 2];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = GetUShortFromByteArray(source, i * 2, type);
            }

            return array;
        }

        public static ushort[] GetUShortArrayFromString(string val)
        {
            List<ushort> list = new List<ushort>();
            if (val.Contains(' '))
            {
                string[] array = Regex.Split(val, "\\s+", RegexOptions.IgnoreCase);
                string[] array2 = array;
                foreach (string value in array2)
                {
                    list.Add(Convert.ToUInt16(value));
                }
            }
            else
            {
                list.Add(Convert.ToUInt16(val));
            }

            return list.ToArray();
        }

        //
        // 摘要:
        //     将无符号整型某个位赋值
        //
        // 参数:
        //   _Mask:
        //     操作位
        //
        //   a:
        //     操作的整数
        //
        //   flag:
        //     操作数
        //
        // 返回结果:
        //     返回整数
        public static ushort SetIntegerSomeBit(int _Mask, ushort a, bool flag)
        {
            a = ((!flag) ? Convert.ToUInt16(a & ~(1 << _Mask)) : Convert.ToUInt16(a | (1 << _Mask)));
            return a;
        }
    }
}